import { useState } from 'react';
import { useForm } from '@tanstack/react-form';
import { useNavigate } from 'react-router-dom';
import { PhoneIcon, CheckIcon, LockClosedIcon } from '@heroicons/react/24/outline';
import type { FieldApi } from '@tanstack/react-form';

import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import registerApis from '../../apis/auth/register';
import { toastError } from '../../components/toast-error';
import OnlyIfUnauthenticated from '../../components/biz/OnlyIfUnauthenticated';
import Card from '../../components/ui/Card';
import VcodeButton from '../../components/util/VcodeButton';

export default function RegisterPage() {
  return (
    <OnlyIfUnauthenticated>
      <RegisterForm />
    </OnlyIfUnauthenticated>
  );
}

function RegisterForm() {
  const navigate = useNavigate();

  const form = useForm({
    defaultValues: {
      phone: '',
      vcode: '',
      password: '',
    },
    onSubmit: ({ value }) => {
      // TODO: loading
      registerApis
        .register({ phone: value.phone, vcode: value.vcode, password: value.password })
        .then((res) => {
          navigate('/login');
          console.log('注册成功', res);
        })
        .catch((err) => {
          toastError(err);
        });
    },
  });

  const [phone, setPhone] = useState('');

  return (
    <div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
      <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
        <Card noPadding className="px-8 py-12">
          <h2 className="mb-6 text-center text-2xl font-bold tracking-tight text-gray-900">在此注册</h2>
          <form.Provider>
            <form
              className="space-y-6"
              onSubmit={(e) => {
                e.preventDefault();
                e.stopPropagation();
                void form.handleSubmit();
              }}
            >
              <form.Field
                name="phone"
                validators={{
                  onChange: ({ value }) => {
                    if (!value) return '手机号不能为空';
                    if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式不正确';
                    return undefined;
                  },
                }}
                children={(field) => {
                  return (
                    <div>
                      <div className="mt-2 relative">
                        <div className=" absolute flex items-center inset-y-0 pl-3 ">
                          <PhoneIcon className="w-4 h-4" />
                        </div>
                        <Input
                          name={field.name}
                          type="text"
                          autoComplete="new-password"
                          block
                          className="pl-9"
                          value={field.state.value}
                          onBlur={field.handleBlur}
                          onChange={(e) => {
                            setPhone(e.target.value);
                            field.handleChange(e.target.value);
                          }}
                          required
                          placeholder="请在此输入手机号"
                        />
                      </div>
                      <FieldInfo field={field} />
                    </div>
                  );
                }}
              />

              <form.Field
                name="vcode"
                validators={{
                  onChange: ({ value }) => {
                    if (!value) return '验证码不能为空';
                    if (!/^\d{6}$/.test(value)) return '验证码格式不正确';
                    return undefined;
                  },
                }}
                children={(field) => {
                  return (
                    <div>
                      <div className="mt-2 flex relative">
                        <div className=" absolute flex items-center inset-y-0 pl-3 ">
                          <CheckIcon className="w-4 h-4" />
                        </div>
                        <Input
                          name={field.name}
                          autoComplete="new-password"
                          type="text"
                          block
                          noRound
                          className="pl-9 rounded-l-md"
                          value={field.state.value}
                          onBlur={field.handleBlur}
                          onChange={(e) => field.handleChange(e.target.value)}
                          required
                          placeholder="请输入验证码"
                        />
                        <VcodeButton phone={phone} sendVcodeApi={registerApis.sendVcode} />
                      </div>
                      <FieldInfo field={field} />
                    </div>
                  );
                }}
              />

              <form.Field
                name="password"
                validators={{
                  onChange: ({ value }) => {
                    if (!value) return '密码不能为空';
                    if (!/^[a-zA-Z0-9`~!@#$%^&*()_+-=[\]{}\\|:;"'<,>.?/]{8,32}$/.test(value)) return '密码格式不正确';
                    return undefined;
                  },
                }}
                children={(field) => {
                  return (
                    <div>
                      <div className="mt-2 relative">
                        <div className=" absolute flex items-center inset-y-0 pl-3 ">
                          <LockClosedIcon className="w-4 h-4" />
                        </div>
                        <Input
                          name={field.name}
                          type="password"
                          autoComplete="new-password"
                          block
                          className="pl-9"
                          value={field.state.value}
                          onBlur={field.handleBlur}
                          onChange={(e) => field.handleChange(e.target.value)}
                          required
                          placeholder="请输入密码"
                        />
                      </div>
                      <FieldInfo field={field} />
                    </div>
                  );
                }}
              />

              <form.Subscribe
                selector={(state) => [state.canSubmit, state.isSubmitting]}
                children={([canSubmit, isSubmitting]) => {
                  return (
                    <div>
                      <Button type="submit" className="flex w-full justify-center">
                        登录 {isSubmitting} {canSubmit}
                      </Button>
                    </div>
                  );
                }}
              />
            </form>
          </form.Provider>
        </Card>
      </div>
    </div>
  );
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function FieldInfo({ field }: { field: FieldApi<any, any, any, any> }) {
  return (
    <>
      {field.state.meta.touchedErrors ? (
        <em className="text-sm text-red-400">{field.state.meta.touchedErrors}</em>
      ) : null}
      {field.state.meta.isValidating ? 'Validating...' : null}
    </>
  );
}
